<?php
namespace Api\Controller;
use Think\Log;
use Think\Controller;
use Think\Controller\RestController;
use Com\Wechat\Jssdk\Jssdk;
use Com\Wechat\JsApiPay;
use Com\Wechat\lib\WxPayUnifiedOrder;
use Com\Wechat\lib\WxPayApi;
use Com\Wechat\WechatApi;
use Com\Wechat\Wechat;
use Com\Wechat\TemplateMessage;
use Com\Wechat\lib\WxPayNotify;
use Think\Exception;
use Com\Wechat\AccessToken;
use Com\Wechat\Card\Signature;
class PayNotifyCallBack extends WxPayNotify
{
  //查询订单
  public function Queryorder($transaction_id)
  {
    return true;
  }

  //重写回调处理函数
  public function NotifyProcess($data, &$msg)
  {
    Log::record("call back:" . json_encode($data),'WARN');
    $notfiyOutput = array();

    if(!array_key_exists("transaction_id", $data)){
      $msg = "输入参数不正确";
      return false;
    }
    //查询订单，判断订单真实性
    if(!$this->Queryorder($data["transaction_id"])){
      $msg = "订单查询失败";
      return false;
    }
    else{
      //判断该笔订单是否在商户网站中已经做过处理
      $out_trade_no = $data["out_trade_no"];
      $order = M('payment')->where(array('id'=>$out_trade_no))->find();
      if(!$order){
        die('未找到订单');
      }
      else if($order['status'] == 1) {
        echo '此订单已支付成功';
      }
      else {
        M('payment')->where(array('id'=>$out_trade_no))->save(array('status'=>1,'pay_time'=>time()));
        //根据ticket_id是否为null判断查哪张表
        if($order['category']==='1'){//票务订单处理
          $re = M('ticket_order')->find($order['order_num']);
          if($re){
            M('ticket_order')->where(array('id'=>$order['order_num']))->save(array('status'=>1));
            $code = array();
            // 成功后生成兑换码
            for($i=0;$i<$re['amount'];$i++){
              $data['ticket_order_id'] = $re['id'];
              $data['create_time'] = time();

              $visitor = M('visitor')->find($re['visitor_id']);

              $data['visitor_phone'] = $visitor['phone'];
              $re_redeem = M('ticket_redeem_code')->add($data);
              $len = strlen($re_redeem);
              $id = substr($re_redeem,($len-2));
              M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
              array_push($code,$data['create_time'].$id);
            }
            //票务库存减少
            $re_ticket = M('ticket')->where(array('id'=>$re['ticket_id']))->find();
            M('ticket')->where(array('id'=>$re['ticket_id']))->save(array('stock'=>$re_ticket['stock']-$re['amount']));

            $exhibition = M('exhibition')
            ->field('exhibition.*,ticket.name as ticket_name')
            ->join("ticket on ticket.id = ".$re['ticket_id'])
            ->where('ticket.exhibition_id = exhibition.id')
            ->find();
            $code_string = implode(',',$code);
            A('User')->sendOrderSuccess($visitor['phone'],$exhibition['name'],$exhibition['ticket_name'],$re['amount'],$code_string);
          }else{
            $msg = "原始订单查询失败";
            return false;
          }
        }
        if($order['category']==='2'){//商品订单处理
          $re_product_order = M('product_order')->find($order['order_num']);
          if($re_product_order){
            //商品订单改变
            M('product_order')->where(array('id'=>$order['order_num']))->save(array('status'=>1));
            //商品库存减少
            $ids = explode(',',$re_product_order['cart_ids']);
            $products = array();
            foreach ($ids as $key => $value) {
              $cart = M('cart')
              ->where(array('cart.id'=>$value))
              ->find();
              $re_attr = M('product_attribution')
              ->field('product_attribution.*,product.name as product_name')
              ->where(array('product_attribution.id'=>$cart['attribution_id']))
              ->join('product on product.id = product_attribution.product_id')
              ->find();
              M('product_attribution')->where(array('id'=>$cart['attribution_id']))->save(array('stock'=>$re_attr['stock']-$cart['quantity']));
              $s_productinfo = $re_attr['product_name'].$re_attr['name'].'x'.$cart['quantity'];
              array_push($products,$s_productinfo);
            }
            //给工作人员推送模板消息
            $visitor = M('visitor')->where(array('id'=>$re_product_order['visitor_id']))->find();
            $products = implode(',',$products);
            $data = array(
              'first'=>array('value'=>'用户'.$visitor['phone'].'已成功购买商品！', 'color'=>'#4a4a4a'),
              'keyword1'=>array('value'=>$re_product_order['order_num'], 'color'=>'#4A90E2'),
              'keyword2'=>array('value'=>$products, 'color'=>'#4A90E2'),
              'keyword3'=>array('value'=>$re_product_order['total'], 'color'=>'#4A90E2'),
              'remark'=>array('value'=>'请及时发货', 'color'=>'#4a4a4a')
            );
            $url = SERVER_PATH.'/home/index/index';
            $templateId = '4klOQBZJVl44Tvx9KOyLJXxzotmWJ7VfGZuSDHOZs-A';
            $openid_vicky = 'o7TmJuKn80VvfWSjRq2G5SfFMg10';
            $openid_hu = 'o7TmJuKdkUYezypDWe8SO80hvkuM';//id86号员工
            $template = new TemplateMessage();
            $template->sendTemplateMessage($data, $openid_vicky, $templateId, $url);
            $template->sendTemplateMessage($data, $openid_hu, $templateId, $url);
          }else{
            $msg = "原始订单查询失败";
            return false;
          }
        }
        if($order['category']==='3'){//会员购买
          $re_vip_order = M('vip_order')->find($order['order_num']);
          if(!$re_vip_order){
            $msg = "原始订单查询失败";
            return false;
          }
          $data['status']=1;
          $data['start_time']=time();
          $data['end_time']=strtotime("+1 year");
          M('vip_order')->where(array('id'=>$order['order_num']))->save($data);
          $date = date('Ymd',time());
          M('visitor')->where(array('id'=>$re_vip_order['visitor_id']))->save(array('vipcode'=>'SFAM_V'.$date.$re_vip_order['vip_type'].$re_vip_order['visitor_id']));
        }
      }
    }
    return true;
  }
}

class WechatController extends BaseController{
  public function getSignPackage(){
    $url = I('get.url');
    $jssdk = new Jssdk();
    $signPackage = $jssdk->getSignPackage($url);
    $this->response($signPackage, 'JSON');
  }

  public function sendTemplateMessage($data, $openid, $templateId, $url){
    $template = new TemplateMessage();
    $return = $template->sendTemplateMessage($data, $openid, $templateId, $url);
    $this->response(array('info'=>$return),'json',200);
  }

  public function downloadImage(){
    $media_id = I('get.media_id');
    $jssdk = new Jssdk();
    $file = $jssdk->getMedia($media_id);
    if(!$file){
      $this->response(array('msg'=>$jssdk->errmsg),'JSON', 500);
    }
    $fileDirver = new \Think\Storage\Driver\File();// 实例化上传类 
    $filePath = './Uploads/Images/'.date('Y-m-d/').uniqid('').'.jpg';

    try{
      $fileDirver->put($filePath ,$file);
    }
    catch (\Think\Exception $e){
      $this->response(array('msg'=>$e->getMessage()), 'JSON', 500);
    }

    $filePath = substr($filePath, 1);
    $this->response(array('info'=>$filePath),'json',200);
  }

  //创建菜单
  public function createToMenus(){
    $WechatApi = new WechatApi();
    $url1 ="http://awq.xoncology.com/Home/index/index/";
    $menu =  array(
      "button"=>
      array( 
       array('type'=>'view','name'=>'“走遍中国前列县(腺)”网络科普公益活动','url'=>$url1)
       )
      );

    $data =$WechatApi->createMenu($menu);
    foreach ($data as $key => $value) {
      \Think\Log::write($value,'WARN');
    }
    $re = $WechatApi->getMenu();
    foreach ($re as $key => $value) {
      dump($re['menu']['button']);
      \Think\Log::write($value,'WARN');
    }
  }

  public function valid(){
    $token ='abcdefg';
    $wechat = new Wechat($token);
    $data = $wechat->request();

    foreach ($data as $key => $value) {
        \Think\Log::write($key,'WARN');
        \Think\Log::write($value,'WARN');
    }
    if($data['Event']=='unsubscribe'){
      //取消关注事件，
      return;
    }
    $WechatApi =new WechatApi();
    $open_id = $data['FromUserName'];
    
    if($data['Event'] =='subscribe'){
      //未关注的
      $text = '欢迎关注“扁鹊医疗”网络科普公益平台，“扁鹊医疗”是由癌症防治领域专业人员共同发起的网络科普公益平台，普及癌症防治知识，服务广大群众。特别声明：本平台不对社会做任何形式的募资！';
      $type='text';
      $wechat->response($text,$type);
    }
  }

  /**
  *票券下单 post
  *@param: ticket_id,amount
  *@return:
  */
  public function confirmTicketOrder(){
    $post = json_decode(file_get_contents('php://input'), true);
    if(!$post['ticket_id']){
      $this->response(array('info'=>'参数错误'),json,400);
    }
    if(!$post['amount']||$post['amount']<=0){
      $this->response(array('info'=>'请选择至少一张票进行购买'),json,400);
    }

    //查询ticket信息
    $re_ticket = M('ticket')->find($post['ticket_id']);
    //查询exhibition信息
    $re_exhibition = M('exhibition')->find($re_ticket['exhibition_id']);
    $body = $re_exhibition['name'].$re_ticket['name'];

    //票券错误信息处理
    $current_date = time();
    if($current_date<$re_ticket['begin_date']){
      $this->response(array('info'=>'很抱歉，您选择的票券还未开售！'),json,400);
    }
    if($current_date>($re_ticket['end_date']+3600*24)){
      $this->response(array('info'=>'很抱歉，您选择的票券已停售！'),json,400);
    }
    if($re_ticket['stock']<=0){
      $this->response(array('info'=>'很抱歉，您选择的票券已售罄！'),json,400);
    }

    //检查活动人数上限
    if($re_exhibition['limit']>0){
      $paied_num = M('ticket_order')
      ->join('ticket on ticket.id = ticket_order.ticket_id','left')
      ->where(array('ticket.exhibition_id'=>$re_ticket['exhibition_id'],'ticket_order.status'=>1))
      ->field('sum(amount) as count')
      ->select();
      if($paied_num[0]['count']>=$re_exhibition['limit']){
        $this->response(array('info'=>'很抱歉，您购买的场次已达人数上限！'),json,400);
      }
    }

    $wechat_session = session('wechat_info');
    if(!$wechat_session){
      $this->response(array('info'=>'请用微信登录！'),json,400);
    }
    $uid = cookie('visitor_id');
    $user = M('visitor')->find($uid);
    $visitor = M('visitor')->where(array('openid'=>$wechat_session['openid'],'phone'=>$user['phone']))->find();
    if(!$visitor){
      $re_user = M('visitor')->where(array('id'=>$uid))->find();
      M('visitor')->where(array('id'=>$uid))->save(array('openid'=>$wechat_session['openid'],'nickname'=>$wechat_session['nickname']));
      if(!$re_user['name']){
        M('visitor')->where(array('id'=>$uid))->save(array('name'=>$wechat_session['nickname']));
      }
    }

    //查询用户信息
    $re_visitor = M('visitor')->find($uid);

    //查询会员信息
    $vip_check=M('vip_order')
    ->where(array('visitor_id'=>$uid))
    ->order('end_time desc')
    ->find();
    // 判断会员有效信息
    if($vip_check&&$vip_check['end_time']>time()){
      $is_vip = true;
    }

    $post['create_time'] = time();
    $post['visitor_id'] = $uid;

    //记录价格
    $post['price'] = $re_ticket['price'];
    $post['activity_price'] = $re_ticket['price_activity'];

    // 生成ticket_order订单
    $re_order = M('ticket_order')->add($post);
    $date = date("Ymd");
    // 更新订单号
    M('ticket_order')->where(array('id'=>$re_order))->save(array('order_num'=>$date.$re_order));

    //生成支付订单
    $payment['order_num'] = $re_order;
    $payment['visitor_id'] = $uid;
    $payment['payment'] = 1;//1微信支付 2支付宝
    $payment['category'] = 1;
    $payment['price'] = $is_vip? ($post['activity_price'] * $post['amount']):($post['price'] * $post['amount']);
    $payment['create_time'] = time();
    $re_payment = M('payment')->add($payment);

    //更新ticket_order支付订单信息
    M('ticket_order')->where(array('id'=>$re_order))->save(array('payment_num'=>$re_payment,'payment'=>$payment['payment']));

    if($payment['price']>0){
      // 微信支付
      $this->wxpay($re_payment,$body);
    }else{//票价免费或为vip用户价格为0
      M('payment')->where(array('id'=>$re_payment))->save(array('status'=>1,'pay_time'=>time()));
      M('ticket_order')->where(array('id'=>$re_order))->save(array('status'=>1));

      $code = array();
      // 成功后生成兑换码
      for($i=0;$i<$post['amount'];$i++){
        $data['ticket_order_id'] = $re_order;
        $data['create_time'] = time();
        $data['visitor_phone'] = $re_visitor['phone'];
        $re_redeem = M('ticket_redeem_code')->add($data);
        $len = strlen($re_redeem);
        $id = substr($re_redeem,($len-2));
        M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
        array_push($code,$data['create_time'].$id);
      }
      //票务库存减少
      M('ticket')->where(array('id'=>$re_ticket['id']))->save(array('stock'=>$re_ticket['stock']-$post['amount']));

      $exhibition = M('exhibition')
      ->field('exhibition.*,ticket.name as ticket_name')
      ->join("ticket on ticket.id = ".$re_ticket['id'])
      ->where('ticket.exhibition_id = exhibition.id')
      ->find();
      $code_string = implode(',',$code);
      A('User')->sendOrderSuccess($re_visitor['phone'],$exhibition['name'],$exhibition['ticket_name'],$post['amount'],$code_string);
      $this->response(array('info'=>'购票成功！请至公众号菜单「我的门票」中查看兑换码。'),json,200);
    }
  }


  /**
  *支付 post
  *@param: order_id
  *@return:
  */
  public function wxpay($order_id,$body) {
    if(!$order_id){
      $this->response(array('info'=>'缺少支付订单号'),'json',400);
    }
    $order = M('payment')->where(array('id'=>$order_id))->find();
    if(!$order){
      $this->response(array('info'=>'未查到订单'),'json',400);
    }

    if($order['status'] === '1'){
      $this->response(array('info'=>'您已经支付过订单了'),'json',400);
    }

    $notify_url = $this->getReturnUrl('wxNotify');
    //①、获取用户openid
    $tools = new JsApiPay();
    $uid = $this->securityTest();
    $user = M('visitor')->find($uid);
    if(!$user['openid']) {
      $this->response(array('info'=>'请在微信端打开'),'json',400);
    }
    $openId = $user['openid'];
    //②、统一下单
    $out_trade_no = $order['id'];
    $input = new WxPayUnifiedOrder();
    $input->SetBody($body);
    $input->SetOut_trade_no($out_trade_no);
    $input->SetTotal_fee(intval($order['price']*100));
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetNotify_url($notify_url);
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);
    $order = WxPayApi::unifiedOrder($input);
    $jsApiParameters = $tools->GetJsApiParameters($order);
    \Think\Log::record($jsApiParameters,'WARN');
    $this->response($jsApiParameters,'');
  }

  public function getReturnUrl($actionKey){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    $result = $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    $result =  explode('/', $result);
    array_splice($result, -1, 1, $actionKey);
    $return_url = implode('/', $result);
      return $return_url;
  }

  public function wxNotify(){
    Log::record('begin notify','WARN');
    $notify = new PayNotifyCallBack();
    $notify->Handle(false);
  }

  /**
  *小程序票券下单 post
  *@param: ticket_id,amount
  *@return:
  */
  public function miniConfirmTicketOrder(){
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)){
     $_POST = (array)json_decode(file_get_contents('php://input'), true);
    }
    $post = I('post.');
    if(!$post['ticket_id']){
      $this->response(array('info'=>'参数错误'),json,400);
    }
    if(!$post['amount']||$post['amount']<=0){
      $this->response(array('info'=>'请选择至少一张票进行购买'),json,400);
    }

    //查询ticket信息
    $re_ticket = M('ticket')->find($post['ticket_id']);
    //查询exhibition信息
    $re_exhibition = M('exhibition')->find($re_ticket['exhibition_id']);
    $body = $re_exhibition['name'].$re_ticket['name'];

    //票券错误信息处理
    $current_date = time();
    if($current_date<$re_ticket['begin_date']){
      $this->response(array('info'=>'很抱歉，您选择的票券还未开售！'),json,400);
    }
    if($current_date>($re_ticket['end_date']+3600*24)){
      $this->response(array('info'=>'很抱歉，您选择的票券已停售！'),json,400);
    }
    if($re_ticket['stock']<=0){
      $this->response(array('info'=>'很抱歉，您选择的票券已售罄！'),json,400);
    }

    //检查活动人数上限
    if($re_exhibition['limit']>0){
      $paied_num = M('ticket_order')
      ->join('ticket on ticket.id = ticket_order.ticket_id','left')
      ->where(array('ticket.exhibition_id'=>$re_ticket['exhibition_id'],'ticket_order.status'=>1))
      ->field('sum(amount) as count')
      ->select();
      if($paied_num[0]['count']>=$re_exhibition['limit']){
        $this->response(array('info'=>'很抱歉，您购买的场次已达人数上限！'),json,400);
      }
    }

    // $wechat_session = session('wechat_info');
    // if(!$wechat_session){
    //   $this->response(array('info'=>'请用微信登录！'),json,400);
    // }
    $userid = $post["userid"];
    $uid = $userid?$userid:cookie('visitor_id');
    $user = M('visitor')->find($uid);

    $map_user['openid'] = $uid;
    $map_user['mini_openid'] = $uid;
    $map_user['_logic'] = 'or';

    $visitor = M('visitor')
    ->where(array('phone'=>$user['phone']))
    ->where($map_user)
    ->find();
    
    if(!$visitor){
      $re_user = M('visitor')->where(array('id'=>$uid))->find();
      M('visitor')->where(array('id'=>$uid))->save(array('openid'=>$user['openid'],'nickname'=>$user['nickname']));
      if(!$re_user['name']){
        M('visitor')->where(array('id'=>$uid))->save(array('name'=>$user['nickname']));
      }
    }

    //查询用户信息
    $re_visitor = M('visitor')->find($uid);

    //查询会员信息
    $vip_check=M('vip_order')
    ->where(array('visitor_id'=>$uid))
    ->order('end_time desc')
    ->find();
    // 判断会员有效信息
    if($vip_check&&$vip_check['end_time']>time()){
      $is_vip = true;
    }

    $post['create_time'] = time();
    $post['visitor_id'] = $uid;

    //记录价格
    $post['price'] = $re_ticket['price'];
    $post['activity_price'] = $re_ticket['price_activity'];

    // 生成ticket_order订单
    $re_order = M('ticket_order')->add($post);
    $date = date("Ymd");
    // 更新订单号
    M('ticket_order')->where(array('id'=>$re_order))->save(array('order_num'=>$date.$re_order));

    //生成支付订单
    $payment['order_num'] = $re_order;
    $payment['visitor_id'] = $uid;
    $payment['payment'] = 1;//1微信支付 2支付宝
    $payment['category'] = 1;
    $payment['price'] = $post['price'] * $post['amount'];
    // $payment['price'] = 0.01;
    $payment['create_time'] = time();
    $re_payment = M('payment')->add($payment);

    //更新ticket_order支付订单信息
    M('ticket_order')->where(array('id'=>$re_order))->save(array('payment_num'=>$re_payment,'payment'=>$payment['payment']));

    if($payment['price']>0){
      // 微信支付
      $this->miniwxpay($re_payment,$body,$user['mini_openid']);
    }else{//票价免费或为vip用户价格为0
      M('payment')->where(array('id'=>$re_payment))->save(array('status'=>1,'pay_time'=>time()));
      M('ticket_order')->where(array('id'=>$re_order))->save(array('status'=>1));

      $code = array();
      // 成功后生成兑换码
      for($i=0;$i<$post['amount'];$i++){
        $data['ticket_order_id'] = $re_order;
        $data['create_time'] = time();
        $data['visitor_phone'] = $re_visitor['phone'];
        $re_redeem = M('ticket_redeem_code')->add($data);
        $len = strlen($re_redeem);
        $id = substr($re_redeem,($len-2));
        M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
        array_push($code,$data['create_time'].$id);
      }
      //票务库存减少
      M('ticket')->where(array('id'=>$re_ticket['id']))->save(array('stock'=>$re_ticket['stock']-$post['amount']));

      $exhibition = M('exhibition')
      ->field('exhibition.*,ticket.name as ticket_name')
      ->join("ticket on ticket.id = ".$re_ticket['id'])
      ->where('ticket.exhibition_id = exhibition.id')
      ->find();
      $code_string = implode(',',$code);
      A('User')->sendOrderSuccess($re_visitor['phone'],$exhibition['name'],$exhibition['ticket_name'],$post['amount'],$code_string);
      $this->response(array('info'=>'购票成功！请至公众号菜单「我的门票」中查看兑换码。'),json,200);
    }
  }

  /**
  *小程序支付 post
  *@param: order_id
  *@return:
  */
  public function miniwxpay($order_id,$body,$mini_openid) {
    if(!$order_id){
      $this->response(array('info'=>'缺少支付订单号'),'json',400);
    }
    $order = M('payment')->where(array('id'=>$order_id))->find();
    if(!$order){
      $this->response(array('info'=>'未查到订单'),'json',400);
    }

    if($order['status'] === '1'){
      $this->response(array('info'=>'您已经支付过订单了'),'json',400);
    }

    $notify_url = $this->getReturnUrl('wxNotify');
    //①、获取用户openid
    $tools = new JsApiPay();
    $user = M('visitor')->where(array('mini_openid'=>$mini_openid))->find();
    
    $openId = $mini_openid;
    //②、统一下单
    $out_trade_no = $order['id'];
    $input = new WxPayUnifiedOrder();
    $input->SetBody($body);
    $input->SetOut_trade_no($out_trade_no);
    $input->SetTotal_fee(intval($order['price']*100));
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetNotify_url($notify_url);
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);
    $order = WxPayApi::miniUnifiedOrder($input);
    
    $jsApiParameters = $tools->GetJsApiParameters($order);
    \Think\Log::record($jsApiParameters,'WARN');
    $this->response($jsApiParameters,'');
  }

  /**
  *商品结算 post
  *@param: orderId,addressId
  *@return:
  */
  public function payProductOrder(){
    $post = json_decode(file_get_contents('php://input'), true);
    if(!$post['orderId']){
      $this->response(array('info'=>'未检测到订单id'),json,400);
    }
    if(!$post['addressId']){
      $this->response(array('info'=>'未检测到地址id'),json,400);
    }
    $orderId = $post['orderId'];
    $addressId = $post['addressId'];
    //查询订单信息
    $re_product_order = M('product_order')
    ->where(array('id'=>$orderId))
    ->find();

    //保存地址id
    M('product_order')
    ->where(array('id'=>$orderId))
    ->save(array('address_id'=>$addressId));   

    //查询cart商品信息
    if(strlen($re_product_order['cart_ids'])>0){
      $ids = explode(',',$re_product_order['cart_ids']);
      $products = array();
      $total = 0;
      foreach ($ids as $key => $value) {
        $product = M('cart')
        ->field('cart.*,product_attribution.stock')
        ->where(array('cart.id'=>$value))
        ->join('product_attribution on product_attribution.id = cart.attribution_id')
        ->find();
        if($product['stock']<$product['quantity']){//库存不足 交易关闭
          M('product_order')->where(array('id'=>$orderId))->save(array('status'=>4));
          $this->response(array('info'=>'库存不足，请重新选购'),json,400);
        }
        if($product['activity_price']>0){
          $total = $total + $product['activity_price']*$product['quantity'];
        }else{
          $total = $total + $product['price']*$product['quantity'];
        }
        array_push($products,$product);
      }
    }else{
      $this->response(array('info'=>'订单中没有可结算的商品'),json,400);
    }
    //校验总金额
    if(strval($total)!=$re_product_order['total']){
      M('product_order')->where(array('id'=>$orderId))->save(array('status'=>5));
      $this->response(array('info'=>'金额校验失败，请重新下单'),json,400);
    }

    //更新用户信息，没有保存过openid的保存
    $wechat_session = session('wechat_info');
    if(!$wechat_session){
      $this->response(array('info'=>'未登录，请用微信登录！'),json,401);
    }
    
    $uid = cookie('visitor_id');
    $user = M('visitor')->find($uid);
    $visitor = M('visitor')->where(array('openid'=>$wechat_session['openid'],'phone'=>$user['phone']))->find();
    if(!$visitor){
      $re_user = M('visitor')->where(array('id'=>$uid))->find();
      M('visitor')->where(array('id'=>$uid))->save(array('openid'=>$wechat_session['openid'],'nickname'=>$wechat_session['nickname']));
      if(!$re_user['name']){
        M('visitor')->where(array('id'=>$uid))->save(array('name'=>$wechat_session['nickname']));
      }
    }

    //生成支付订单
    $payment['order_num'] = $orderId;
    $payment['visitor_id'] = $uid;
    $payment['payment'] = 1;//暂时为1微信支付
    $payment['category'] = 2;//1 票务订单 2 商品订单
    $payment['price'] = $re_product_order['total'];
    $payment['create_time'] = time();
    $re_payment = M('payment')->add($payment);

    //更新product_order支付订单信息
    M('product_order')->where(array('id'=>$orderId))->save(array('payment_num'=>$re_payment,'payment'=>$payment['payment']));

    // 微信支付
    $body = '商品订单'.$re_product_order['order_num'];
    $this->wxpay($re_payment,$body);
    
  }

  /**
  *vip支付 post
  *@param: type会员种类,表单
  *@return:
  */
  public function buyVipOrder(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    if(!$post['type']){
      $this->response(array('info'=>'请选择会员种类'),json,400);
    }
    //表单共有项检测必填
    if(!$post['name']||!$post['phone']||!$post['email']||!$post['idcard']||!$post['focustype']||!$post['gender']){
      $this->response(array('info'=>'登记表中有必填项未填写，请完善信息后再次提交！'),json,400);
    }
    //会员种类
    $vip_type = M('membership')->find($post['type']);
    //表单特有项检测必填
    switch($vip_type['id']){
      case 1:
      if(!$post['studentcard']||!$post['school']){
        $this->response(array('info'=>'登记表中有必填项未填写，请完善信息后再次提交！'),json,400);
      };break;
      case 2:
      if(!$post['edu']||!$post['job']){
        $this->response(array('info'=>'登记表中有必填项未填写，请完善信息后再次提交！'),json,400);
      };break;
      case 3:
      if(!$post['family_num']){
        $this->response(array('info'=>'登记表中有必填项未填写，请完善信息后再次提交！'),json,400);
      };break;
      default:return;
    }
    $post['create_time'] = time();
    $post['uid'] = $uid;
    //添加到vip登记表
    $re_record = M('viprecord')->add($post);
    if(!$re_record){
      $this->response(array('info'=>'登记表添加失败，请重新提交！'),json,400);
    }

    //创建vip_order订单
    $vip_order['visitor_id']=$uid;
    $vip_order['create_time']=time();
    $vip_order['membership_title']=$vip_type['title'];
    $vip_order['price']=$vip_type['price'];
    $vip_order['vip_type']=$vip_type['id'];

    $new_viporder = M('vip_order')->add($vip_order);
    //更新order_num
    $date = date("Ymd");
    M('vip_order')->where(array('id'=>$new_viporder))->save(array('order_num'=>'V'.$date.$new_viporder));

    //更新用户信息，没有保存过openid的保存
    $wechat_session = session('wechat_info');
    if(!$wechat_session){
      $this->response(array('info'=>'未登录，请用微信登录！'),json,401);
    }
    
    $user = M('visitor')->find($uid);
    $visitor = M('visitor')->where(array('openid'=>$wechat_session['openid'],'phone'=>$user['phone']))->find();
    if(!$visitor){
      $re_user = M('visitor')->where(array('id'=>$uid))->find();
      M('visitor')->where(array('id'=>$uid))->save(array('openid'=>$wechat_session['openid'],'nickname'=>$wechat_session['nickname']));
      if(!$re_user['name']){
        M('visitor')->where(array('id'=>$uid))->save(array('name'=>$wechat_session['nickname']));
      }
    }

    //生成支付订单
    $payment['order_num'] = $new_viporder;
    $payment['visitor_id'] = $uid;
    $payment['payment'] = 1;//暂时为1微信支付
    $payment['category'] = 3;//会员购买
    $payment['price'] = $vip_type['price'];
    $payment['create_time'] = time();
    $re_payment = M('payment')->add($payment);

    //更新ticket_order支付订单信息
    M('vip_order')->where(array('id'=>$new_viporder))->save(array('payment_num'=>$re_payment,'payment'=>$payment['payment']));

    // 微信支付
    $body = '会员购买订单'.'V'.$date.$new_viporder;
    $this->wxpay($re_payment,$body);
  }

  /**
  *获取accesstoken 
  *@param: 
  *@return:
  */
  public function getAccesstoken(){
    $accessToken = AccessToken::getAccessToken();
    $this->response(array('info'=>$accessToken),json,200);
  }

  /**
  *添加到卡包 post
  *@param: 
  *@return:
  */
  public function addToWechatCardWallet(){
    $uid = $this->securityTest();
    $user = M('visitor')->find($uid);
    if(!$user['openid']){
      $this->response(array('info'=>'查找用户失败，请重新登录'),json,401);
    }
    $post = json_decode(file_get_contents('php://input'), true);
    $card = $post['data'];
    $accessToken = AccessToken::getAccessToken();
    //创建卡券
    $posturl = "https://api.weixin.qq.com/card/create?access_token=".$accessToken;
    $data_string = json_encode($card,JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $posturl);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response,true);
    $this->response(array('info'=>$response),json,200);
  }

  /**
  *修改卡券内容 post
  *@param: 
  *@return:
  */
  public function editWechatCard(){
    $post = json_decode(file_get_contents('php://input'), true);
    $card = $post['data'];
    $accessToken = AccessToken::getAccessToken();
    //创建卡券
    $posturl = "https://api.weixin.qq.com/card/update?access_token=".$accessToken;
    $data_string = json_encode($card,JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $posturl);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response,true);
    $this->response(array('info'=>$response),json,200);
  }

  /**
  *删除卡券 post
  *@param: 
  *@return:
  */
  public function deleteWechatCard(){
    $card['card_id'] = I('get.code');
    if(!$card['card_id']){
      $this->response(array('info'=>'code码不可为空'),json,400);
    }
    $accessToken = AccessToken::getAccessToken();
    //删除卡券
    $posturl = "https://api.weixin.qq.com/card/delete?access_token=".$accessToken;
    $data_string = json_encode($card,JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $posturl);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response,true);
    $this->response(array('info'=>$response),json,200);
  }

  /**
  *设置卡券测试白名单 post
  *@param: 
  *@return:
  */
  public function wechatCardTestId(){
    $test_username = I('get.username');
    if(!$test_username){
      $this->response(array('info'=>'code码不可为空'),json,400);
    }
    $accessToken = AccessToken::getAccessToken();
    $posturl = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=".$accessToken;
    $data['username'] = array();
    array_push($data['username'], $test_username);
    $data_string = json_encode($data,JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $posturl);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response,true);
    $this->response(array('info'=>$response),json,200);
  }

  /**
  *获取api_ticket post
  *@param: 
  *@return:
  */
  public function wechatCardApiTicket(){
    $uid = $this->securityTest();
    //查找会员
    $re_visitor = M('visitor')->find($uid);
    if(!$re_visitor||!$re_visitor['openid']||!$re_visitor['vipcode']){
      $this->response(array('info'=>'用户信息查找失败，请重新登录'),json,400);
    }
    //查找vip订单
    $vip_check=M('vip_order')
    ->where(array('visitor_id'=>$uid))
    ->order('end_time desc')
    ->find();
    if(!$vip_check){
      $this->response(array('info'=>'会员信息查找失败，请重新登录'),json,400);
    }

    $api_ticket = cookie('api_ticket',null);
    if(!$api_ticket){
      $accessToken = AccessToken::getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$accessToken."&type=wx_card";

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      $response = curl_exec($ch);
      curl_close($ch);
      $response = json_decode($response,true);
      if($response['ticket']){
        $api_ticket = $response['ticket'];
        cookie('api_ticket',$api_ticket,7200);
      }else{
        $this->response(array('info'=>$response),json,400);
      }
    }
    switch($vip_check['vip_type']){
      case '1': $card_id = 'p7TmJuAC_qNQWZs3_UFLDrqa01cQ';break;
      case '2': $card_id = 'p7TmJuA82OClxAGOWpRLjqV02WGw';break;
      case '3': $card_id = 'p7TmJuOrp96p6IVJHG-AyP319bGE';break;
      default: $this->response(array('info'=>'会员卡信息错误'),json,400);
    }
    $data['code'] = $re_visitor['vipcode'];
    $data['openid'] = $re_visitor['openid'];
    $data['timestamp'] = time();
    $data['fixed_begintimestamp'] = time();

    $signature = new Signature();
    $signature->add_data($api_ticket);
    $signature->add_data($data['timestamp']);
    $signature->add_data($card_id);
    $signature->add_data($data['code']);
    $signature->add_data($data['openid']);
    $data['signature'] = $signature->get_signature();
    $data = json_encode($data);
    $this->response(array('info'=>$data,'card_id'=>$card_id,'api_ticket'=>$api_ticket),json,200);
  }

  /**
  *新增会员 get
  *@param: 
  *@return:
  */
  public function addVipMmber(){
    $phone = I('get.phone');
    $type = I('get.type');
    if(!$phone||!$type){
      $this->response(array('info'=>'参数不可为空'),json,400);
    }
    $re_user = M('visitor')->where(array('phone'=>$phone))->find();
    if(!$re_user){
      $this->response(array('info'=>'未查询到该用户'),json,400);
    }
    if($re_user['vipcode']){
      $this->response(array('info'=>'该用户已经是会员'),json,400);
    }
    $re_type = M('membership')->find($type);
    if(!$re_type){
      $this->response(array('info'=>'未查询到该种类的会员卡'),json,400);
    }

    //创建vip_order订单
    $vip_order['visitor_id']=$re_user['id'];
    $vip_order['create_time']=time();
    $vip_order['membership_title']=$re_type['title'];
    $vip_order['price']=0;
    $vip_order['vip_type']=$type;
    $vip_order['start_time']=time();
    $vip_order['end_time']=strtotime("+1 year");
    $vip_order['status']=1;
    $vip_order['remark']='后台添加';
    $new_viporder = M('vip_order')->add($vip_order);

    $date = date("Ymd");
    M('vip_order')->where(array('id'=>$new_viporder))->save(array('order_num'=>'V'.$date.$new_viporder));
    M('visitor')->where(array('phone'=>$phone))->save(array('vipcode'=>'SFAM_V'.$date.$type.$re_user['id']));

    $this->response(array('info'=>'添加成功'),json,200);
  }

  /**
  *永久二维码
  *@param: 
  *@return:
  */
  public function foreverQrcode(){
    $accessToken = AccessToken::getAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$accessToken;

    $data['action_name'] = "QR_LIMIT_SCENE";
    $data['action_info'] = array(
      'scene' => array(
        "scene_id" => '123'
      )
    );

    $data_string = json_encode($data,JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string);
    $response = curl_exec($ch);
    curl_close($ch);
    $response = json_decode($response,true);

    $this->response(array('info'=>$response),json,200);
  }
}